#include <iostream>
#include <QMessageBox>
#include <QFileDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <boost/shared_ptr.hpp>
#include "riskmeasure/RiskMeasureReader.h"
#include "riskmeasure/RiskMeasureDot.h"
#include "gui/dotgraphview.h"
#include "gui/riskmeasureeditor.h"

using namespace quic;
using namespace std;
using namespace boost;

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
{    
    ui->setupUi(this);
    riskmeasureEditor = new RiskMeasureEditor(ui, this);
    connect(this, SIGNAL(riskMeasureLoaded(bool)),ui->actionZoom_In, SLOT(setEnabled(bool)));
    connect(this, SIGNAL(riskMeasureLoaded(bool)),ui->actionZoom_Out, SLOT(setEnabled(bool)));
    connect(ui->riskMeasureTable, SIGNAL(clicked(QModelIndex)),riskmeasureEditor, SLOT(riskMeasureSelected(QModelIndex)));
    ui->scrollArea->setGeometry(QRect(0,0,400,400));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::menuOpen()
{
    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Open Image"), ".", tr("CSV Files (*.csv)"));

    cout << "Opened " << fileName.toStdString() << endl;
    RiskMeasureReader reader;
    try {
        cout << "Started renering graph" << endl;
        shared_ptr<RiskMeasure> riskMeasure = reader.read(fileName.toStdString());
        this->riskMeasureTableModel.setRiskMeasure(riskMeasure);
        this->riskmeasureEditor->setRiskMeasureRoot(riskMeasure);
        RiskMeasureDot dot;
        QString imageFileName = dot.renderDotGraph(riskMeasure);
        cout << "Graph rendered" << endl;

        QImage image(imageFileName);
        if (image.isNull()) {
            QMessageBox::information(this, tr("Image Viewer"),
                                     tr("Cannot load %1.").arg(imageFileName));
            return;
        }

        // Setup the graph
        DotGraphView *dotGraphView = new DotGraphView(image);
        connect(ui->actionZoom_In,SIGNAL(triggered()),
                dotGraphView,SLOT(zoomIn()));
        connect(ui->actionZoom_Out,SIGNAL(triggered()),
                dotGraphView,SLOT(zoomOut()));
        ui->scrollArea->setWidget(dotGraphView);                

        // setup the table
        ui->riskMeasureTable->setModel(&riskMeasureTableModel);

        emit riskMeasureLoaded(true);
    }
    catch(string &exception)
    {
        cout << exception << endl;
        emit riskMeasureLoaded(false);
    }
}
